package cn.imatu.framework.web.error;

import cn.imatu.framework.core.response.Resp;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author shenguangyang
 */
@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class LyErrorController extends BasicErrorController {

    public LyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties,
                             List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
        Assert.notNull(errorProperties, "ErrorProperties must not be null");
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        return super.errorHtml(request, response);
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = this.getStatus(request);
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        if (status == HttpStatus.NOT_FOUND) {
            Resp<?> response = Resp.fail("Not found path " + body.get("path"));
            return new ResponseEntity<>(JSONObject.from(response), status);
        }
        return new ResponseEntity<>(JSONObject.from(Resp.fail()), status);
    }

}
